import ListEmpty from '@/components/antd-comp/empty'
import TableGrid from '@/components/antd-comp/table'
import { columnsProps } from '@/components/antd-comp/table/constants'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import { bsConfirm } from '@/components/bs-ui/alertDialog/useConfirm'
import FouterPage from '@/components/fouter-page'
import InputAntDef from '@/components/input/InputAntDef'
import { useRouteStoreHook } from '@/store/routeStore'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { delRoleApi, getRolesApi } from '../../../controllers/API/user'
import { captureAndAlertRequestErrorHoc } from '../../../controllers/request'
import { ROLE } from '../../../types/api/user'
import EditRole from './EditRole'
import './style/index.less'

// table的唯一id
const getUniqueKey = (record: any) => record.id

export default function Roles() {
  useRouteStoreHook(['组织架构'])
  const { t } = useTranslation()

  const [loading, setLoading] = useState(false)
  const [role, setRole] = useState<Partial<ROLE> | null>(null)
  const [roles, setRoles] = useState<ROLE[]>([])
  const allRolesRef = useRef([])

  const handleChange = (change: boolean) => {
    change && loadData()
    setRole(null)
  }

  const loadData = () => {
    setLoading(true)
    getRolesApi().then((data: any) => {
      setRoles(data)
      allRolesRef.current = data
      setLoading(false)
    })
  }

  useEffect(() => loadData(), [])

  // 删除
  const handleDelete = item => {
    bsConfirm({
      desc: `${t('system.confirmText')} 【${item.role_name}】 ?`,
      okTxt: t('delete'),
      onOk(next) {
        captureAndAlertRequestErrorHoc(delRoleApi(item.id).then(loadData))
        next()
      }
    })
  }

  // 验证重名
  const checkSameName = (name: string) => {
    return roles.find(_role => _role.role_name === name && role.id !== _role.id)
  }

  // search
  const [searchWord, setSearchWord] = useState('')
  const handleSearch = e => {
    const word = e.target.value
    setSearchWord(word)
    setRoles(allRolesRef.current.filter(item => item.role_name.toUpperCase().includes(word.toUpperCase())))
  }

  if (role)
    return (
      <EditRole
        id={role.id || -1}
        name={role.role_name || ''}
        onBeforeChange={checkSameName}
        onChange={handleChange}
      ></EditRole>
    )

  // 定义tableColumns
  const tableColumns: columnsProps[] = [
    {
      dataIndex: 'role_name',
      title: t('system.roleName'),
      width: 140,
      render: (text, _record, _index) => text || '--'
    },
    {
      dataIndex: 'create_time',
      title: t('createTime'),
      width: 180,
      render: (text, _record, _index) => text?.replace('T', ' ')
    },
    {
      dataIndex: 'operation',
      title: t('operations'),
      fixed: 'right',
      width: 160,
      render: (_text, record, _index) => (
        <div className="ml-[-16px] bg-inherit">
          <span onClick={() => setRole(record)} className="tableSettingName ml-[16px] px-0 text-[#062FF8]">
            {t('edit')}
          </span>
          {[1, 2].includes(record.id) ? (
            <span className="tableSettingName ml-[16px] px-0 text-gray-400">{t('delete')}</span>
          ) : (
            <span onClick={() => handleDelete(record)} className="tableSettingName ml-[16px] px-0 text-red-500">
              {t('delete')}
            </span>
          )}
          {/* 为了实现右侧fix时border-radius额外增加的遮罩层 */}
          <div className="common-table-right-fixed-layer2">{''}</div>
          <div className="common-table-right-fixed-layer3">{''}</div>
        </div>
      )
    }
  ]

  return (
    <div className="user-manager-container relative h-full min-w-[600px] bg-[#f5f7fb]">
      {loading && (
        <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
          <span className="loading loading-infinity loading-lg"></span>
        </div>
      )}
      <div className="absolute left-0 top-0 m-[32px] rounded-[6px] bg-[#ffffff]">
        <div className="flexRowJustBet flex py-[24px] pl-[24px] pr-[32px]">
          <div className="flexRowStart">
            <InputAntDef searchFun={handleSearch} placeholder={t('system.roleName')}></InputAntDef>
          </div>
          <div className=" flex items-center justify-end gap-4">
            <ThemeBtn className="migu-font-600 h-[36px] w-[92px]" onClick={() => setRole({})}>
              {t('create')}
            </ThemeBtn>
          </div>
        </div>

        <div className="relative top-[0] h-[calc(100vh-196px)] max-h-[calc(100vh-196px)] overflow-y-scroll px-[24px] scrollbar-hide">
          <TableGrid
            tableInfo={{
              tableData: roles,
              tableColumns,
              getUniqueKey, // 唯一id
              scrollHeight: 'calc(100vh - 294px)',
              scrollWidth: 500
            }}
            emptyComponent={
              !loading && !roles?.length ? (
                <ListEmpty style={{ height: 'calc(100vh - 314px)', margin: 0 }} />
              ) : (
                <div style={{ height: 'calc(100vh - 314px)', background: '#ffffff', margin: 0 }}></div>
              )
            }
          />
        </div>
        <FouterPage
          className="sys-footer-common-bottom-box sys-footer-common-gray-text rounded-[6px]"
          style={{ background: '#FFFFFF' }}
          page={1}
          pageSize={1000}
          total={1000}
          setPage={() => {}}
        ></FouterPage>
      </div>
    </div>
  )
}
